import cv2 as cv
import numpy as np
from utils.methods import generateImg
from pitchtime.pitch import PitchV
from pitchtime.pitchData import guitar, humming, letmego
import os
import re
import shutil

musics = {
  'm1': guitar,
  'm2': humming,
  'm3': letmego
}

musicsPath = {
  'm1': 'pitchtime/crop_music/guitar_crop.aac',
  'm2': 'pitchtime/crop_music/humming_crop.aac',
  'm3': 'pitchtime/crop_music/letmego_crop.aac'
}

# 读取模板图片
def osTemplates(path):
  templatesExit = os.path.exists(path)
  if templatesExit == False:
    raise OSError('模板文件夹不存在')
  files = os.listdir(path)
  length = len(files)
  tData = []
  for i, item in enumerate(files):
    if i+1 >= len(files):
      break
    tem = []
    tem.append(f'{path}/{files[i]}')
    tem.append(f'{path}/{files[i+1]}')
    tData.append(tem)
  t0 = [
    f'{path}/{files[length-1]}',
    f'{path}/{files[0]}'
  ]  
  tData.insert(0, t0)
  return tData, files  

### 生成视频   path: 图片素材路径  outpath: 视频输出路径
def generateVideo(path, outputPath, music):
  tData = osTemplates(path)[0]
  files = osTemplates(path)[1]
  pv = PitchV(outputPath)
  frames = musics[music]

  if music == 'temporary':
    for i, item in enumerate(frames):
      index = i % len(tData)
      bg = cv.imread(tData[index][0])
      front = cv.imread(tData[index][1])
      if i == 0:
        pv.unfoldPitch(bg, front, item, 0)
      else:  
        pv.unfoldPitch(bg, front, item, 3)  


  for i, item in enumerate(frames):
    index = i % len(tData)
    bg = cv.imread(tData[index][0])
    front = cv.imread(tData[index][1])
    if i == 0:
      pv.opacityPitch(bg, front, item, 0)
    else:  
      transform = 4 if music == 'm2' else 0
      pv.opacityPitch(bg, front, item, 4)   

# 合成图片并生成视频
def buildVideo(assetsPath, videoPath, music):
  templatePath = os.path.join(assetsPath, 'templates')
  assetsExit = os.path.exists(assetsPath)
  templateExit = os.path.exists(templatePath)
  if assetsExit == False:
    raise OSError('素材文件夹不存在')
  if templateExit == False:
    os.mkdir(templatePath)
  else:
    shutil.rmtree(templatePath)
    os.mkdir(templatePath)

  vName = videoPath.split('/')[-1]
  vPath = assetsPath + '/' + vName
  files = os.listdir(assetsPath)
  for i, item in enumerate(files):
    match = re.search(r'\.(jpg|png|jpeg|gif|webp|svg)', item, re.I)
    if match == False or match == None:
      continue
    template = os.path.join(assetsPath, item)
    img = cv.imread(template)
    resPath = os.path.join(templatePath, f't{i+1}.jpg')
    generateImg(img, outputPath=resPath, filters='')

  generateVideo(templatePath, vPath, music)  
  projectPath = os.getcwd()
  musicPath = os.path.join(projectPath, musicsPath[music])
  os.system(f'ffmpeg -i {vPath} -i {musicPath} -vf "movie=logo.png[watermark];[in][watermark] overlay=main_w-overlay_w-10:main_h-overlay_h-4[out] " -bsf:a aac_adtstoasc -strict -2 -y {videoPath}')
  shutil.rmtree(templatePath)
